package com.major.queue.sparsearray;

public class SparseArray {
    public static void main(String[] args) {
        // 原始的数组
        // 1 表示 黑，2 表示 白
        int[][] chess = new int[11][11];
        chess[1][2] = 1;
        chess[1][3] = 1;
        chess[2][3] = 2;
        chess[5][2] = 1;
        // 遍历
        System.out.println("原始二维数组：");
        for (int[] row : chess) {
            for (int item : row) {
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }

        // 二维数组 转换为 稀疏数组
        int sum = 0;
        for (int i = 0; i < chess.length; i++){
            for (int j = 0; j < chess[0].length; j++){
                if (chess[i][j] != 0) sum++;
            }
        }
        System.out.println(sum);
        // 稀疏数组
        int[][] sparseArray = new int[sum + 1][3];
        sparseArray[0][0] = chess.length;
        sparseArray[0][1] = chess[0].length;
        sparseArray[0][2] = sum;
        // 赋值
        int row = 1;
        for (int i = 0; i < chess.length; i++){
            for (int j = 0; j < chess[0].length; j++){
                if (chess[i][j] != 0) {
                    sparseArray[row][0] = i;
                    sparseArray[row][1] = j;
                    sparseArray[row][2] = chess[i][j];
                    row++;
                }
            }
        }
        // 遍历稀疏数组
        System.out.println("得到的稀疏数组为：");
        for (int i = 0; i < sparseArray.length; i++){
            System.out.printf("%d\t%d\t%d\t\n",sparseArray[i][0],sparseArray[i][1],sparseArray[i][2]);
        }
        /*for (int[] ints : sparseArray){
            for (int item : ints) {
                System.out.printf("%d\t",item);
            }
            System.out.println();*/


        // 稀疏数组恢复为二维数组
        // 建立合适的二维数组
        int row2 = sparseArray[0][0];
        int col2 = sparseArray[0][1];
        int[][] toChess = new int[row2][col2];
        // 赋值
        for (int i = 1; i < sparseArray.length; i++) {
            toChess[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }



/*        int sparseRow = 1;
        //int numRow = sparseArray[sparseRow][0];
        for (int i = 0; i < row2; i++) {

            for (int j = 0; j < col2; j++) {

                if (i == sparseArray[sparseRow][0] && j == sparseArray[sparseRow][1]){
                    toChess[i][j] = sparseArray[1][2];
                    //sparseRow++;
                }
            }

        }*/
        System.out.println("===============================");
        // 遍历
        System.out.println("恢复的二维数组为：");
        for (int[] row3 : toChess) {
            for (int item : row3) {
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }
    }
}
